//
//  Common.m
//  HB
//
//  Created by 陶秋安 on 16/2/19.
//  Copyright © 2016年 孙智慧. All rights reserved.
//

#import "Common.h"
#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"

@implementation Common

+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+(BOOL)isVerifyPwd:(NSString *)pwd
{
    NSString * strPwd = @"^[a-zA-Z]{1}[a-zA-Z0-9_]{5,19}$";
    NSPredicate *regextestpwd = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", strPwd];
    if([regextestpwd evaluateWithObject:pwd] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+(void)showMsg:(NSString *) msg andCancel:(BOOL) hasCancel andHost:(id)host
{
    UIAlertController *alertController=[[UIAlertController alloc] init];
    alertController.message=msg;
    if(hasCancel)
    {
        UIAlertAction *alertAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:alertAction];
    }
    [host presentViewController:alertController animated:YES completion:nil];
}

+(NSString *)createMD5:(NSString *)signString
{
    const char*cStr =[signString UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    return[NSString stringWithFormat:
           @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
           result[0], result[1], result[2], result[3],
           result[4], result[5], result[6], result[7],
           result[8], result[9], result[10], result[11],
           result[12], result[13], result[14], result[15]
           ];
}

//创建风火轮
+ (void)createActivityView:(UIView *)img
{
    static int size = 40;
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    activityView.translatesAutoresizingMaskIntoConstraints=NO;
    
    activityView.color=[UIColor whiteColor];
    
    [img addSubview:activityView];
    
    //ImageView顶部与父视图顶部对齐
    NSLayoutConstraint *centerXConstraint = [NSLayoutConstraint constraintWithItem:activityView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:img attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f];
    
    //ImageView底部与父视图顶部对齐
    NSLayoutConstraint *centerYConstraint = [NSLayoutConstraint constraintWithItem:activityView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:img attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f];
    
    //ImageView高度为父视图高度
    NSLayoutConstraint* heightConstraint = [NSLayoutConstraint constraintWithItem:activityView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:size];
    
    //ImageView宽度为父视图宽度
    NSLayoutConstraint* widthConstraint = [NSLayoutConstraint constraintWithItem:activityView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:size];
    
    [img addConstraints:@[centerXConstraint,centerYConstraint,heightConstraint,widthConstraint]];
    
    [activityView startAnimating];
    
}

//移除风火轮
+ (void)stopActivityView:(UIView *)img
{
    
    for (UIView *view in [img subviews])
    {
        //读出UIButton里的所有控件，再选择UIActivityIndicatorView进行更改
        if ([view isKindOfClass:[UIActivityIndicatorView class]])
        {
            //把风火轮UIActivityIndicatorView移除
            [view removeFromSuperview];
            
        }
    }
    
}


+ (BOOL)checkLanchExist:(NSString *)fileName
{
    //NSString *fileName = [FxDate stringFromDateYMD:[NSDate date]];
    NSString *filePath = [FxGlobal getCacheImage:fileName];
    
    if ([FxFileUtility isFileExist:filePath]) {
        //self.myimageView .image = [UIImage imageWithContentsOfFile:filePath];
        //进行其他的操作
        return YES;
    }
    
    return NO;
}

+ (BOOL)checkMp3Exist:(NSString *)fileName
{
    //NSString *fileName = [FxDate stringFromDateYMD:[NSDate date]];
    NSString *filePath = [FxGlobal getCacheMp3];
    
    if ([FxFileUtility isFileExist:filePath]) {
        //进行其他的操作
        return YES;
    }
    
    return NO;
}

+(void) setUserDefaults:(NSString *) keyName andValue:(NSString *)value
{
    //存储数据
    NSString *strValue = [NSString stringWithString:value];
    
    NSString *strKey= [NSString stringWithString:keyName];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    [userDefaults setObject:strValue forKey:strKey];
    
    //在存储数据的地方,别忘了这一句
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSString *) getUserDefaults:(NSString *) keyName
{
    //在需要的地方获取数据
    return [[NSUserDefaults standardUserDefaults] objectForKey:keyName];
}

+(void) setCover:(UIImageView *)targetView
{
    //毛玻璃 ----begin-----
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle: UIBlurEffectStyleDark];
    UIVisualEffectView *visualEffectView= [[UIVisualEffectView alloc]initWithEffect:blurEffect];
    visualEffectView.frame = [UIScreen mainScreen].bounds;
    visualEffectView.alpha = 1;
    [targetView addSubview:visualEffectView];
    //毛玻璃 ----end-----
}

//网络监测
+ (NSString *)checkNetworkState
{
    NSString *state=@"0";
    
    // 1.检测wifi状态
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
    // 2.检测手机是否能上网络(WIFI\3G\2.5G)
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    // 3.判断网络状态
    if ([wifi currentReachabilityStatus] != NotReachable)
    {
        // 有wifi
        state=@"1";
        
    }
    else if ([conn currentReachabilityStatus] != NotReachable)
    {
        // 没有使用wifi, 使用手机自带网络进行上网
        state=@"2";
        
    } else
    {
        // 没有网络
        state=@"0";
        
    }
    
    return  state;
}


+ (void) downLoadImageByURL:(UIImageView *) view andURL:(NSString *) imgPath andName:(NSString *)imgName
{
    if([Common checkLanchExist:imgName])
    {
        NSString *filePath = [FxGlobal getCacheImage:imgName];
        
        UIImage *img= [UIImage imageWithContentsOfFile:filePath];
        
        dispatch_async( dispatch_get_main_queue(), ^(void)
                       {
                           
                           [view setImage:img];
                           
                           [Common stopActivityView:view];
                           
                       });
        
    }
    else
    {
        //这里把imageBlock当做了一个变量，它封装了一段代码，这段代码在-(void)AdImg:(NSArray*)arr中
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
                       {
                           NSData * data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgPath]];
                           
                           [data writeToFile:[FxGlobal getCacheImage:imgName] atomically:YES];
                           
                           UIImage * image = [[UIImage alloc] initWithData:data];
                           
                           dispatch_async( dispatch_get_main_queue(), ^(void)
                                          {
                                              if( image != nil )
                                              {
                                                  [view setImage:image];
                                                  
                                                  [Common stopActivityView:view];
                                              }
                                          });
                       });
    }
}

+(NSString*)getCacheSize
{
    
    NSDate* begin = [NSDate date];
    
    NSFileManager* fm = [NSFileManager defaultManager];
    
    __block NSError* error = nil;
    
    __block NSUInteger fileSize = 0;
    
    NSString *path = [NSString stringWithFormat:@"%@/%@", [FxGlobal getRootPath], CacheImagePath];
    //获取Books的缓存
    //dispatch_sync(dispatch_get_main_queue(), ^{
    
    NSArray* subFiles = [fm subpathsAtPath:path];
    
    NSLog(@"subpath = %@",subFiles);
    
    for (NSString* fileName in subFiles)
    {
        if ([fileName hasSuffix:@"png"]||[fileName hasSuffix:@"jpg"])
        {
            NSDictionary* dic = [fm attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@",path,fileName] error:&error];
            NSUInteger size = (error ? 0:[dic fileSize]);
            fileSize += size;
        }
    }
    
    
    path = [NSString stringWithFormat:@"%@/%@", [FxGlobal getRootPath], DownLoadPath];
 
    subFiles = [fm subpathsAtPath:path];
    
    NSLog(@"subpath = %@",subFiles);
    
    for (NSString* fileName in subFiles)
    {
        if ([fileName hasSuffix:@"png"]||[fileName hasSuffix:@"jpg"] || [fileName hasSuffix:@"mp3"])
        {
            NSDictionary* dic = [fm attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@",path,fileName] error:&error];
            NSUInteger size = (error ? 0:[dic fileSize]);
            fileSize += size;
        }
    }
    
    path = [NSString stringWithFormat:@"%@/%@", [FxGlobal getRootPath], CacheMusicPath];

    subFiles = [fm subpathsAtPath:path];
    
    NSLog(@"subpath = %@",subFiles);
    
    for (NSString* fileName in subFiles)
    {
        if ([fileName hasSuffix:@"png"]||[fileName hasSuffix:@"jpg"] || [fileName hasSuffix:@"mp3"])
        {
            NSDictionary* dic = [fm attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@",path,fileName] error:&error];
            NSUInteger size = (error ? 0:[dic fileSize]);
            fileSize += size;
        }
    }

    
    
    NSString* cacheString = [NSString stringWithFormat:@"%.2fM",fileSize/(1024.0*1024)];
    NSTimeInterval time = [begin timeIntervalSinceNow];
    NSLog(@"便利文件耗费时间:%lf",time/60.0);
    return cacheString;
}

+(void) clearCache:(id)host sel:(SEL)sel
{
    
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   , ^{
                       //NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                       NSString *cachPath = [NSString stringWithFormat:@"%@/%@", [FxGlobal getRootPath], CacheImagePath];
                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath ];
                       
                       for (NSString *p in files) {
                           NSError *error;
                           NSString *path = [cachPath stringByAppendingPathComponent:p];
                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       }
                       [host performSelectorOnMainThread:sel withObject:nil waitUntilDone:YES];
                   });
    
}

+(NSDate*) convertDateFromString:(NSString*)uiDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *date=[formatter dateFromString:uiDate];
    
    return date;
}

+(NSString *) convertSize:(NSInteger)size
{
    CGFloat ii= size/1024.0;
    
    return [NSString stringWithFormat:@"%.2fM",ii];
}

+(NSString *) checkMusicIsExists:(NSString *)musicID qualityID:(NSString *)qualityID
{
    NSString *downloadPath=  [NSString stringWithFormat:@"%@/%@_%@.%@",[FxGlobal getDownLoad],musicID,qualityID,@"mp3"];
    
    if([FxFileUtility isFileExist:downloadPath])
    {
        return downloadPath;
    }
    
    return @"";
    
}

+(NSString *) checkCacheMusciIsExists:(NSString *)musicID qualityID:(NSString *)qualityID
{
    NSString *cachePath=  [NSString stringWithFormat:@"%@/%@_%@.%@",[FxGlobal getCacheMp3],musicID,qualityID,@"mp3"];
    
    if([FxFileUtility isFileExist:cachePath])
    {
        return cachePath;
    }
    
    return @"";
}


@end
